package com.bbcare.treat.plat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IScanDataSynchService;
import com.bbcare.followup.plat.service.impl.PatientService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientOperationRecordDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.plat.redis.service.IPatientQueueRedis;
import com.bbcare.treat.plat.entity.FuQueueScheme;
import com.bbcare.treat.plat.entity.PtArchiveData;
import com.bbcare.treat.plat.entity.PtArchiveTask;
import com.bbcare.treat.plat.entity.PtTrContentData;
import com.bbcare.treat.plat.entity.PtTrQueue;
import com.bbcare.treat.plat.entity.PtTrTask;
import com.bbcare.treat.plat.entity.TrTask;
import com.bbcare.treat.plat.entity.TrTaskContent;
import com.bbcare.treat.plat.service.IPatientTreatService;
import com.bbcare.treat.plat.service.IPtTaskTreatService;
import com.bbcare.treat.plat.store.ibatis.IFuQueueSchemeDAO;
import com.bbcare.treat.plat.store.ibatis.IPtArchiveDataDAO;
import com.bbcare.treat.plat.store.ibatis.IPtArchiveTaskDAO;
import com.bbcare.treat.plat.store.ibatis.IPtTrContentDataDAO;
import com.bbcare.treat.plat.store.ibatis.IPtTrQueueDAO;
import com.bbcare.treat.plat.store.ibatis.IPtTrTaskDAO;
import com.bbcare.treat.plat.store.ibatis.ITrSchemeDAO;
import com.bbcare.treat.plat.store.ibatis.ITrTaskContentDAO;
import com.bbcare.treat.plat.store.ibatis.ITrTaskDAO;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

/**
 * @name: 患者门诊诊疗相关接口实现
 * @author:
 * @createTime: 2017.8.15
 * @description:
 * @modify:
 *
 */
@Service
public class PtTaskTreatService implements IPtTaskTreatService {
    private final Log logger = LogFactory.getLog(PtTaskTreatService.class);

    /*
     * @Autowired private IFuQueueSchemeDAO fuQueueSchemeDao;
     */
    @Autowired
    private ITrSchemeDAO iTrSchemeDAO;
    @Autowired
    private ITrTaskContentDAO ITrTaskContentDao;
    @Autowired
    private IFuQueueSchemeDAO IFuQueueSchemeDAO;
    @Autowired
    private PatientTreatService PatientTreatService;
    @Autowired
    private IPtTrTaskDAO IPtTrTaskDAO;
    @Autowired
    private ITrTaskDAO ITrTaskDAO;
    @Autowired
    private IPtTrContentDataDAO IPtTrContentDataDAO;
    @Autowired
    private IFollowQueueDAO IFollowQueueDAO;
    @Autowired
    private IFollowQueueDAO queueDao;
    @Autowired
    private IPatientDAO patientDao;
    @Autowired
    private IPatientInfoHisService patientInfoHisService;
    @Autowired
    private IPatientOperationRecordDAO patientOperationRecordDao;
    @Autowired
    private IPtTrQueueDAO IPtTrQueueDAO;
    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;
    @Autowired
    public IConfCacheDAO IConfCacheDAO;
    @Autowired
    private IPatientTaskDAO patientTaskDao;
    @Autowired
    private PatientService PatientService;
    @Autowired
    private IPatientTaskContentDAO patientTaskConDao;
    @Autowired
    private IPtArchiveTaskDAO ptArchiveTaskDao;
    @Autowired
    private IPtArchiveDataDAO ptArchiveDataDao;
    @Autowired
    private ITrTaskDAO trTaskDao;
    @Autowired
    private IPatientTreatService patientTreatService;
    @Autowired
    private IFollowQueueService followQueueSerivce;
    @Autowired
    private IPatientQueueRedis ptQueueRedis;
    @Resource(name = "jedisPool")
    private JedisPool jedisPool;
    @Autowired
    private IScanDataSynchService scanDataSynchService;

    /**
     * @name: 查询队列关联方案信息
     * @author: wuyz
     * @createTime: 2017.8.17
     * @description:查询队列关联方案信息
     * @modify:
     *
     */
    @Override
    public Map<String, Object> listscheme(Map<String, Object> map) throws Exception {
        logger.info("listschemeseervice : " + map.toString());
        List<FuQueueScheme> listone = IFuQueueSchemeDAO.getTrSchemeBusiTypeByQueueId(map);
        List<Map<String, Object>> listTow = new ArrayList<Map<String, Object>>();
        // 查询当前队列的方案类型
        if (listone != null && listone.size() > 0) {
            for (int i = 0; i < listone.size(); i++) {
                Map<String, Object> mapOne = new HashMap<String, Object>();
                FuQueueScheme fu = listone.get(i);
                mapOne.put("schemeBusiType", fu.getSchemeBusiType());
                map.put("schemeBusiType", fu.getSchemeBusiType());
                List<Map<String, Object>> list = iTrSchemeDAO.getTrSchemeListByQueueId(map);
                mapOne.put("rows", list);
                listTow.add(i, mapOne);
            }
        }
        Map<String, Object> mapOut = new HashMap<String, Object>();
        List<FollowQueue> fu = new ArrayList<FollowQueue>();
        map.put("id", map.get("queueId"));
        fu = IFollowQueueDAO.selectById(map);
        if (fu != null && fu.size() > 0) {
            mapOut.put("queueName", fu.get(0).getQueueName());
        } else {
            mapOut.put("queueName", "");
        }
        mapOut.put("schemeList", listTow);

        return mapOut;
    }

    /**
     * @name: 查询当前任务模板
     * @author: wuyz
     * @createTime: 2017.8.17
     * @description:查询当前任务模板
     * @modify:
     *
     */
    @Override
    public Map<String, Object> qryTaskContent(Map<String, Object> map) throws Exception {
        // logger.info("qryTaskContent : " + map.toString());
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> questionMap = new HashMap<String, Object>();
        // logger.info("mapqryTaskContent:" + map.toString());
        int schemeBusiType = Integer.parseInt(String.valueOf(map.get("schemeBusiType")));
        if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
            List<TrTaskContent> list = ITrTaskContentDao.getTaskContentByTaskId(map);
            if (list != null && list.size() > 0) {
                String archiveTemplId = "";
                for (int i = 0; i < list.size(); i++) {
                    TrTaskContent tc = list.get(i);
                    archiveTemplId = archiveTemplId + "," + tc.getTemplId();
                }
                String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
                List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
                Map<String, Object> contMapIn = new HashMap<String, Object>();
                contMapIn.put("templIdList", archiveTemplIdList);
                Map<String, Object> contMapOut = PatientTreatService.getContentTemplData(contMapIn);
                retOut.put("questiones", contMapOut.get("questiones"));
            }

            if (!StringUtils.isBlank((String) map.get("ptSchemeId"))) {
                List<PtArchiveTask> ptVoList = ptArchiveTaskDao.listPtArchiveTask(map);
                if (!CollectionUtils.isEmpty(ptVoList)) {
                    // 患者建档问卷答案信息
                    Map<String, Object> cntMap = new HashMap<String, Object>();
                    cntMap.put("ptTaskId", ptVoList.get(0).getId());
                    List<PtArchiveData> ptConList = ptArchiveDataDao.listPtArchiveData(cntMap);
                    if (!CollectionUtils.isEmpty(ptConList)) {
                        int tt = 0;
                        for (; tt < ptConList.size(); tt++) {
                            PtArchiveData pcdVo = ptConList.get(tt);
                            questionMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                        }
                    }
                }
                /** 修改实现任务名称自动生成 */
                // 后台根据当前任务的记录数，自动计算出新建一笔的任务名称
                map.put("ptShemeId", map.get("ptSchemeId"));
                int currTotal = IPtTrTaskDAO.getOprationHistoryTotal(map);// 获取当前用户填写次数
                List<TrTask> trTaskList = new ArrayList<TrTask>();
                String taskId = (String) map.get("taskId");// 任务id
                if (StringUtils.isNotBlank(taskId)) {
                    Map<String, Object> taskQueryParam = new HashMap<String, Object>();
                    taskQueryParam.put("Id", taskId);
                    trTaskList = trTaskDao.listTrTaskBySchemeVersionid(taskQueryParam);
                }
                TrTask trTaskVo = trTaskList.get(0);
                StringBuffer strBuffer = new StringBuffer();
                strBuffer.append("第");
                String currTotalStr = ToolUtils.toChineseStr(currTotal + 1);
                strBuffer.append(currTotalStr);
                strBuffer.append("次");
                strBuffer.append(trTaskVo.getTaskName());
                retOut.put("defTaskRecordName", strBuffer.toString());
            } else {
                retOut.put("defTaskRecordName", "");
            }
        }
        retOut.put("values", questionMap);
        logger.info("qryTaskContent : " + retOut.toString());
        return retOut;
    }

    /**
     * @name: 实例化任务
     * @author: wuyz
     * @createTime: 2017.8.17
     * @description:实例化模板，填写问题和答案入库，可添加和更新
     * @modify: 2017.09.28: DemonLee 门诊记录修改为全部该患者所有任务的list，不是某一项任务的list
     */
    @Override
    @Transactional
    public Map<String, Object> submitTaskFunciton(Map<String, Object> argIn) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(argIn);
        logger.info("submitTaskFunciton : " + map.toString());
        Map<String, Object> mapOut = new HashMap<String, Object>();

        String task = (String) map.get("task");// 获取任务id
        String taskId = (String) map.get("taskId");// 任务实例id
        String opType = (String) map.get("opType");
        String opCode = (String) map.get("opCode");
        String updateAccept = (String) map.get("updateAccept");
        String ptSchemeId = (String) map.get("ptSchemeId");
        String userId = (String) map.get("userId");
        String updateTime = (String) map.get("updateTime");
        String authorId = (String) map.get("authorId");
        String tenantId = (String) map.get("tenantId");
        String authorName = (String) map.get("authorName");
        String queueId = (String) map.get("queueId");
        String finishTime = (String) map.get("finishTime");
        boolean appInvokeFlag = false;// app调用标志
        Integer opRecordDealFlag = (Integer) map.get("opRecordDealFlag");// 离线时先建档，再提交任务，此时不需要再插操作记录
        if (null == opRecordDealFlag) {
            opRecordDealFlag = 0;
        }
        String sourceType = (String) map.get("sourceType");// 来源渠道
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }
        map.put("sourceType", sourceType);

        // 队列信息校验
        HashMap<String, Object> queueInMap = new HashMap<String, Object>();
        queueInMap.put("id", queueId);
        List<FollowQueue> queueList = queueDao.selectById(queueInMap);
        if (CollectionUtils.isEmpty(queueList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到对应队列信息！"));
        }

        String queueUserType = queueList.get(0).getQueueUsertype();
        String userType = "";
        if(Constants.QUEUE_USER_TYPE_BABY.equals(queueUserType)) {
        	userType =Constants.PTUSER_PATIENT_USER_TYPE_BABY;
        }else if(Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
        	userType = Constants.PTUSER_PATIENT_USER_TYPE_PARTURIENT;
        }else {
        	userType =Constants.PTUSER_PATIENT_USER_TYPE_OTHER;
        }
        map.put("userType", userType);
        // 患者信息
        Map<String, Object> userInMap = new HashMap<String, Object>();
        userInMap.put("userId", userId);
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = queueList.get(0).getTenantId();
            // app调用
            if (StringUtils.isEmpty(tenantId) && appInvokeFlag) {
                tenantId = Constants.PT_USER_INFO_DEFAULT_TENANT_ID;
            }
        }
        userInMap.put("tenantId", tenantId);
        Patient ptOut = patientDao.selectById(userInMap);
        if (null == ptOut) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询无此患者记录！"));
        }
        map.put("tenantId", tenantId);

        Map<String, Object> mapIn = new HashMap<String, Object>();
        Map<String, Object> quesMap = ToolUtils.typeCast(map.get("contentData"));
        if (MapUtils.isEmpty(quesMap)) {
            logger.warn("无问题--答案记录");
            return mapIn;
        }

        // 用task查询当前任务信息
        mapIn.put("Id", task);
        List<TrTask> listTask = ITrTaskDAO.listTrTaskBySchemeVersionid(mapIn);
        if (CollectionUtils.isEmpty(listTask)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "当前无此门诊诊疗任务！"));
        }
        TrTask tt = listTask.get(0);
        map.put("trTaskInfo", tt);
        String taskName = tt.getTaskName();
        String finishDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_OMS_TASKRECORD_DATE);
        if (StringUtils.isBlank(finishDate)) {
            finishDate = DateUtil.getCurrDate2();
        }
        String taskRecordName = (String) quesMap.get(Constants.QUESTION_ID_FOR_OMS_TASKRECORD_NAME);
        if (StringUtils.isBlank(taskRecordName)) {
            taskRecordName = taskName;
        }
        map.put("finishDateStr", finishDate);
        map.put("taskRecordNameStr", taskRecordName);

        // 将当前任务入pt_trtask_info患者诊疗任务信息表,可以多次提交
        // 通过是否有任务实例id判断当前是修改还是新增
        boolean joinFlag = false;
        String newQueueId = (String) quesMap.get(Constants.QUESTION_ID_FOR_LEAVEHOSPITAL_NEW_QUEUE_ID);
        if (StringUtils.isNotBlank(newQueueId) && !queueId.equals(newQueueId)) {
            joinFlag = true;
        }
        if (StringUtils.isBlank(taskId)) {
            // 插入
            taskId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASKID);
            finishTime = DateUtil.getDate_8(new Date());
            map.put("taskId", taskId);
            map.put("finishTime", finishTime);
            this.saveTreatContData(map);
        } else {
            // 更新
            if (joinFlag) {
                // 该字段值是否有变化
                Map<String, Object> questionMap = new HashMap<String, Object>();
                questionMap.put("ptTask", taskId);
                questionMap.put("questionIdStr", Constants.QUESTION_ID_FOR_LEAVEHOSPITAL_NEW_QUEUE_ID);
                List<PtTrContentData> ptTaskConList = IPtTrContentDataDAO.getTaskContent(questionMap);
                if (!CollectionUtils.isEmpty(ptTaskConList)) {
                    String answerStr = ptTaskConList.get(0).getQuestionAnswer();
                    if (null == answerStr) {
                        answerStr = "";
                    }
                    logger.warn("oldQueueId==" + answerStr + ", newQueueId==" + newQueueId);
                    if (newQueueId.equals(answerStr)) {
                        // 值没有变化
                        joinFlag = false;
                    }
                }
            }
            this.modifyTreatContData(map);
        }
        logger.warn("joinFlag==" + joinFlag + ", newQueueId==" + newQueueId);

        // 判断出院登记是否加入一个新的随访队列
        if (joinFlag && Constants.PATIENT_SOURCE_TYPE_DOOR.equals(sourceType)) {
            // 暂时只考虑门诊渠道过来的
            this.dealJoinNewQueue(map);
        }

        // 入操作流水记录表 ia_operation_record
        if (0 == opRecordDealFlag) {
            Map<String, Object> paramRecord = new HashMap<String, Object>();
            paramRecord.put("userName", ptOut.getUserName());
            paramRecord.put("userId", userId);
            paramRecord.put("queueId", queueId);
            paramRecord.put("authorId", authorId);
            paramRecord.put("opTime", updateTime);
            if (Constants.OP_TYPE_SELF.equals(opType)) {
                paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_8);
            } else {
                paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_9);
            }
            if (Constants.OP_TYPE_SELF.equals(opType)) {
                paramRecord.put("opUsertype", Constants.OPCODE_TYPE_PATIENT);
            } else {
                paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
            }
            paramRecord.put("authorName", authorName);
            paramRecord.put("opCode", opCode);
            paramRecord.put("updateAccept", updateAccept);
            paramRecord.put("tenantId", tenantId);
            paramRecord.put("remark", map.get("opNote"));
            paramRecord.put("opType", opType);
            paramRecord.put("taskId", taskId);
            Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
            patientOperationRecordDao.saveOperationRecord(outRecord);
        }

        // redis更新今日门诊时间
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(Constants.REDIS_DB_INDEX_PATIENT);

            // 建档，诊疗和随访都要更新今日门诊，userId※ptSchemeId※姓名
            int dealTime = Integer.parseInt(DateUtil.getHm());// 15:30-->1530
            Map<String, Object> redisMap = new HashMap<String, Object>();
            redisMap.put("queueId", queueId);
            redisMap.put("dealDate", DateUtil.getCurrDate());
            redisMap.put("userId", userId);
            redisMap.put("ptSchemeId", ptSchemeId);
            redisMap.put("userName", ptOut.getUserName());
            redisMap.put("dealTime", dealTime);
            // 先更新诊疗，后续再增加更新随访
            ptQueueRedis.saveOutPatientRedisforQueue(redisMap, jedis);
        } catch (JedisConnectionException jex) {
            logger.error("redis连接异常..." + jex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
        } finally {
            ToolUtils.closeRedis(jedis);
        }
        mapOut.put("ptTaskId", taskId);

        //如果是web后端 且有随访指导内容 则根据规则推送到消息总线
        if(Constants.PATIENT_SOURCE_TYPE_DOOR.equals(sourceType)){
        	map.put("schemeBusiType",Constants.SCHEME_BUSI_TYPE_1);
        	scanDataSynchService.sendFollowGuidance(map);
        }

        return mapOut;
    }

    /**
     * @name: 诊疗任务插入
     * @author: DemonLee
     * @createTime: 2018.3.14
     * @description: 单独封装一个函数
     * @modify:
     */
    public Map<String, Object> saveTreatContData(Map<String, Object> argIn) throws Exception {
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>(argIn);

        Map<String, Object> quesMap = ToolUtils.typeCast(map.get("contentData"));
        String task = (String) map.get("task");// 获取任务id
        String taskId = (String) map.get("taskId");// 任务实例id
        String updateAccept = (String) map.get("updateAccept");
        String ptSchemeId = (String) map.get("ptSchemeId");
        String userId = (String) map.get("userId");
        String updateTime = (String) map.get("updateTime");
        String authorId = (String) map.get("authorId");
        String tenantId = (String) map.get("tenantId");
        String queueId = (String) map.get("queueId");
        String nextDate = (String) map.get("nextDate");
        String nextAddress = (String) map.get("nextAddress");
        String finishTime = (String) map.get("finishTime");
        String taskNote = (String) map.get("taskNote");
        String updateAuname = (String) map.get("updateAuname");
        String finishDate = (String) map.get("finishDateStr");
        String taskRecordName = (String) map.get("taskRecordNameStr");
        // 离线时先建档，再提交任务，此时不需要再插操作记录
        Integer opRecordDealFlag = (Integer) map.get("opRecordDealFlag");
        if (null == opRecordDealFlag) {
            opRecordDealFlag = 0;
        }
        String sourceType = (String) map.get("sourceType");// 来源渠道

        TrTask tt = (TrTask) map.get("trTaskInfo");// 诊疗任务
        String taskName = tt.getTaskName();
        String taskIntro = tt.getTaskIntro();
        int seqNo = tt.getSeqNo();
        String schemeVersionid = tt.getSchemeVersionid();

        // 拼接入参
        PtTrTask ptt = new PtTrTask();
        ptt.setId(taskId);
        ptt.setTaskId(task);
        ptt.setUserId(userId);
        ptt.setPtSchemeId(ptSchemeId);
        ptt.setQueueId(queueId);
        ptt.setTaskName(taskName);
        ptt.setTaskIntro(taskIntro);
        ptt.setSeqNo(seqNo);
        ptt.setAuthorId(authorId);
        ptt.setCreateTime(updateTime);
        ptt.setUpdateTime(updateTime);
        ptt.setUpdateAccept(updateAccept);
        ptt.setUpdateAuthor(authorId);
        ptt.setTaskNote(taskNote);
        if (!StringUtils.isBlank(nextDate)) {
            ptt.setNextDate(nextDate);
        }
        ptt.setNextAddress(nextAddress);
        ptt.setUpdateAuname(updateAuname);
        if (!StringUtils.isBlank(finishTime)) {
            ptt.setFinishTime(finishTime);
        }
        ptt.setTaskRecordName(taskRecordName);
        ptt.setFinishDate(finishDate);
        // 将用户任务实例化
        if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)) {
            // 诊间扫码渠道
            ptt.setAuditStatus(Constants.PATIENT_TASK_AUDIT_STATUS_CHECKING);
        } else if (Constants.PATIENT_SOURCE_TYPE_DOOR.equals(sourceType)) {
            // 门诊渠道
            ptt.setAuditStatus(Constants.PATIENT_TASK_AUDIT_STATUS_NORMAL);
        } else {
            // 后续待扩展
            ptt.setAuditStatus(Constants.PATIENT_TASK_AUDIT_STATUS_INIT);
        }
        IPtTrTaskDAO.savePtTask(ptt);
        ptt.setUpdateType(Constants.UPDATE_TYPE_UPDATE_X);
        ptt.setSchemeVersionid(schemeVersionid);
        IPtTrTaskDAO.savePtTaskHis(ptt);

        // 拼装问题和答案，准备入表pt_trcontentdata_info
        if (MapUtils.isNotEmpty(quesMap)) {
            List<PtTrContentData> ptcInList = new ArrayList<PtTrContentData>();
            Iterator<String> iter = quesMap.keySet().iterator();
            while (iter.hasNext()) {
                PtTrContentData pcdVo = new PtTrContentData();
                String queskey = iter.next();
                String quesvalue = (String) quesMap.get(queskey);
                pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
                pcdVo.setPtTaskId(taskId);
                pcdVo.setTaskId(task);
                pcdVo.setCreateTime(updateTime);
                pcdVo.setQuestionAnswer(quesvalue);
                pcdVo.setQuestionId(queskey);
                pcdVo.setUpdateAccept(updateAccept);
                pcdVo.setUpdateTime(updateTime);
                pcdVo.setPtSchemeId(ptSchemeId);
                pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
                pcdVo.setUserId(userId);
                pcdVo.setQueueId(queueId);
                pcdVo.setTenantId(tenantId);
                pcdVo.setSourceTypeCreate(sourceType);
                pcdVo.setSourceTypeUpdate(sourceType);
                ptcInList.add(pcdVo);
            }
            // 批量插入
            IPtTrContentDataDAO.savePtTrContentDate(ptcInList);
            IPtTrContentDataDAO.savePtTrContentDateHis(ptcInList);
        }

        Map<String, Object> mapQueue = new HashMap<String, Object>();
        // 更新任务完成次数
        List<PtTrQueue> list = IPtTrQueueDAO.getPtTrQueue(map);
        if (CollectionUtils.isEmpty(list)) {
            //
        } else {
            int finishNum = list.get(0).getFinishNum() + 1;
            mapQueue.put("finishNum", finishNum);
            mapQueue.put("ptSchemeId", ptSchemeId);
            mapQueue.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
            mapQueue.put("updateAccept", updateAccept);
            IPtTrQueueDAO.updatePtTrQueueByptSchemeId(mapQueue);
            IPtTrQueueDAO.insertPtTrQueueHis(mapQueue);
        }

        return retOut;
    }

    /**
     * @name: 诊疗任务更新
     * @author: DemonLee
     * @createTime: 2018.3.14
     * @description: 单独封装一个函数
     * @modify:
     */
    public Map<String, Object> modifyTreatContData(Map<String, Object> argIn) throws Exception {
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>(argIn);

        Map<String, Object> quesMap = ToolUtils.typeCast(map.get("contentData"));
        String task = (String) map.get("task");// 获取任务id
        String taskId = (String) map.get("taskId");// 任务实例id
        String updateAccept = (String) map.get("updateAccept");
        String ptSchemeId = (String) map.get("ptSchemeId");
        String userId = (String) map.get("userId");
        String updateTime = (String) map.get("updateTime");
        String authorId = (String) map.get("authorId");
        String tenantId = (String) map.get("tenantId");
        String queueId = (String) map.get("queueId");
        String nextDate = (String) map.get("nextDate");
        String nextAddress = (String) map.get("nextAddress");
        String finishTime = (String) map.get("finishTime");
        String taskNote = (String) map.get("taskNote");
        Integer opRecordDealFlag = (Integer) map.get("opRecordDealFlag");// 离线时先建档，再提交任务，此时不需要再插操作记录
        if (null == opRecordDealFlag) {
            opRecordDealFlag = 0;
        }
        String sourceType = (String) map.get("sourceType");// 来源渠道
        String updateAuname = (String) map.get("updateAuname");
        String finishDate = (String) map.get("finishDateStr");
        String taskRecordName = (String) map.get("taskRecordNameStr");

        TrTask tt = (TrTask) map.get("trTaskInfo");// 诊疗任务
        String schemeVersionid = tt.getSchemeVersionid();

        // 通过用户实例任务id查询用户任务信息
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("Id", taskId);
        List<PtTrTask> lists = IPtTrTaskDAO.listTrTaskByTaskId(mapIn);
        if (CollectionUtils.isEmpty(lists)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "当前患者无此门诊诊疗任务！"));
        }
        PtTrTask currPtTrTask = lists.get(0);
        String taskAuditStatus = currPtTrTask.getAuditStatus();
        if (StringUtils.isBlank(taskAuditStatus)) {
            taskAuditStatus = Constants.PATIENT_TASK_AUDIT_STATUS_INIT;
        } else if (Constants.PATIENT_TASK_AUDIT_STATUS_NORMAL.equals(taskAuditStatus)) {
            // 已审核通过
            if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)) {
                // 诊间扫码渠道
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_PT_SACN_SYNC_DATA_FOR_AUDITED,
                        "患者填写信息医生已确认，无法同步修改！"));
            }
        }
        Map<String, Object> mapOne = new HashMap<String, Object>();
        if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)
                && Constants.PATIENT_TASK_AUDIT_STATUS_INIT.equals(taskAuditStatus)) {
            // 诊间扫码渠道，初始化-->待审核
            mapOne.put("auditStatus", Constants.PATIENT_TASK_AUDIT_STATUS_CHECKING);
        } else if (Constants.PATIENT_SOURCE_TYPE_DOOR.equals(sourceType)) {
            // 门诊渠道更新为审核通过
            mapOne.put("auditStatus", Constants.PATIENT_TASK_AUDIT_STATUS_NORMAL);
        } else {
            // 后续待扩展
        }
        // 将用户任务实例化
        mapOne.put("taskId", taskId);
        mapOne.put("updateTime", updateTime);
        mapOne.put("updateAccept", updateAccept);
        if (StringUtils.isBlank(taskNote)) {
            taskNote = "";
        }
        mapOne.put("taskNote", taskNote);
        if (!StringUtils.isBlank(authorId)) {
            mapOne.put("updateAuthor", authorId);
        }

        if (StringUtils.isBlank(nextDate)) {
            nextDate = null;
        }
        mapOne.put("nextDate", nextDate);

        if (StringUtils.isBlank(nextAddress)) {
            nextAddress = "";
        }
        mapOne.put("nextAddress", nextAddress);

        if (!StringUtils.isBlank(finishTime)) {
            mapOne.put("finishTime", finishTime);
        }
        if (!StringUtils.isBlank(updateAuname)) {
            mapOne.put("updateAuname", updateAuname);
        }
        mapOne.put("updateType", Constants.UPDATE_TYPE_INSERT);
        mapOne.put("schemeVersionid", schemeVersionid);
        mapOne.put("taskRecordName", taskRecordName);
        mapOne.put("finishDate", finishDate);
        IPtTrTaskDAO.updatePatientTrTaskById(mapOne);
        IPtTrTaskDAO.insertPatientTrTaskHisById(mapOne);

        // 逐条更新
        List<PtTrContentData> ptcInListOne = new ArrayList<PtTrContentData>();
        Set<String> keys = quesMap.keySet();
        Map<String, Object> ptUpMapIn = new HashMap<String, Object>();
        int pr = 0;
        for (String key : keys) {
            ptUpMapIn.clear();
            String queskey = key;
            String quesvalue = (String) quesMap.get(queskey);
            ptUpMapIn.put("questionAnswer", quesvalue);
            ptUpMapIn.put("questionId", queskey);
            ptUpMapIn.put("taskId", task);
            ptUpMapIn.put("updateAccept", updateAccept);
            ptUpMapIn.put("updateTime", updateTime);
            ptUpMapIn.put("ptTaskId", taskId);
            ptUpMapIn.put("sourceTypeUpdate", sourceType);
            pr = IPtTrContentDataDAO.updatePtTrContentDatafoByConDt(ptUpMapIn);
            if (0 == pr) {
                PtTrContentData pcdVoOne = new PtTrContentData();
                pcdVoOne.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
                pcdVoOne.setPtTaskId(taskId);
                pcdVoOne.setTaskId(task);
                pcdVoOne.setCreateTime(updateTime);
                pcdVoOne.setQuestionAnswer(quesvalue);
                pcdVoOne.setQuestionId(queskey);
                pcdVoOne.setUpdateAccept(updateAccept);
                pcdVoOne.setUpdateTime(updateTime);
                pcdVoOne.setPtSchemeId(ptSchemeId);
                pcdVoOne.setUpdateType(Constants.UPDATE_TYPE_INSERT);
                pcdVoOne.setUserId(userId);
                pcdVoOne.setQueueId(queueId);
                pcdVoOne.setTenantId(tenantId);
                pcdVoOne.setSourceTypeCreate(sourceType);
                pcdVoOne.setSourceTypeUpdate(sourceType);
                ptcInListOne.add(pcdVoOne);
            }
        }
        if (!CollectionUtils.isEmpty(ptcInListOne)) {
            IPtTrContentDataDAO.savePtTrContentDate(ptcInListOne);
        }
        // 更新历史轨迹
        HashMap<String, Object> hisConDataMap = new HashMap<String, Object>();
        hisConDataMap.put("taskId", taskId);
        hisConDataMap.put("updateAccept", updateAccept);
        hisConDataMap.put("updateTime", updateTime);
        hisConDataMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        IPtTrContentDataDAO.insertPtTrContentDataHis(hisConDataMap);

        return retOut;
    }

    /**
     * @name: 出院登记加入一个新的随访队列
     * @author: DemonLee
     * @createTime: 2018.3.14
     * @description:
     * @modify:
     */
    public Map<String, Object> dealJoinNewQueue(Map<String, Object> argIn) throws Exception {
        logger.debug("---into dealJoinNewQueue---argIn==" + argIn.toString());
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argIn);

        Map<String, Object> contValues = ToolUtils.typeCast(mapIn.get("contentData"));
        String newQueueId = (String) contValues.get(Constants.QUESTION_ID_FOR_LEAVEHOSPITAL_NEW_QUEUE_ID);
        if (StringUtils.isBlank(newQueueId)) {
            return retOut;
        }
        String opNote = (String) mapIn.get("opNote");
        String opType = (String) mapIn.get("opType");
        String authorName = (String) mapIn.get("authorName");
        String updateAccept = (String) mapIn.get("updateAccept");
        String updateTime = (String) mapIn.get("updateTime");
        String authorId = (String) mapIn.get("authorId");
        String sourceType = (String) mapIn.get("sourceType");
        String userId = (String) mapIn.get("userId");
        String oldTenantId = (String) mapIn.get("tenantId");
        String userType = (String) mapIn.get("userType");
        // 队列信息
        Map<String, Object> queueInMap = new HashMap<String, Object>();
        queueInMap.put("id", newQueueId);
        List<FollowQueue> queueList = queueDao.selectById(queueInMap);
        if (CollectionUtils.isEmpty(queueList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到对应队列信息！"));
        }
        FollowQueue fqVo = queueList.get(0);
        // 暂时考虑使用队列的租户id
        String tenantId = fqVo.getTenantId();
        if (!tenantId.equals(oldTenantId)) {
            // 新加入的队列与之前的队列不在一个租户下，暂时不考虑支持
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_JOIN_NON_CURR_TENANT,
                    "暂不支持加入不在当前租户系统下的随访队列！"));
        }
        Integer schemeBusiType = fqVo.getSchemeBusiType();
        if (null == schemeBusiType) {
            // 默认科研随访
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0;
        }
        if (null == opNote) {
            opNote = "加入新随访队列【" + fqVo.getQueueName() + "】";
        }

        // 患者信息
        Map<String, Object> userInMap = new HashMap<String, Object>();
        userInMap.put("userId", userId);
        userInMap.put("tenantId", oldTenantId);
        userInMap.put("userType", userType);
        Patient currPt = patientDao.selectById(userInMap);
        if (null == currPt) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询无此患者记录！"));
        }

        // 是否已加入过该队列
        Map<String, Object> qryPqsMap = new HashMap<String, Object>();
        qryPqsMap.put("userId", userId);
        qryPqsMap.put("queueId", newQueueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT);
        qryPqsMap.put("status", statulist);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(qryPqsMap);
        if (!CollectionUtils.isEmpty(pqsList)) {
            // 已加入该队列，直接返回
            logger.warn("---该患者已加入该队列【" + fqVo.getQueueName() + "】---");
            return null;
        }

        // 查询患者信息及建档资料
        Map<String, Object> servParamMap = new HashMap<String, Object>();
        Patient pt = new Patient();
        pt.setPregnancyDay(currPt.getPregnancyDay());
        pt.setUserName(currPt.getUserName());
        pt.setPhoneNo(currPt.getPhoneNo());
        pt.setFirstName(currPt.getFirstName());
        pt.setCreateTime(updateTime);
        pt.setUpdateTime(updateTime);
        pt.setCreateAuthor(authorId);
        pt.setBirthday(currPt.getBirthday());
        pt.setExpectedDay(currPt.getExpectedDay());
        pt.setGender(currPt.getGender());
        pt.setUserType(currPt.getUserType());
        pt.setSourceType(sourceType);

        servParamMap.put("followQueueId", newQueueId);
        servParamMap.put("userType", currPt.getUserType());
        servParamMap.put("patient", pt);
        servParamMap.put("authorName", authorName);
        servParamMap.put("deptId", fqVo.getDeptId());
        servParamMap.put("queueId", newQueueId);
        servParamMap.put("updateTime", updateTime);
        servParamMap.put("authorId", authorId);
        // 流水与前面的业务区分开（但也要能找到关联）
        servParamMap.put("updateAccept", updateAccept + "_" + SeqUtil.getSeqNoBySize(2));
        servParamMap.put("tenantId", tenantId);
        // 操作编码：建档默认1000
        servParamMap.put("opCode", Constants.OP_CODE_1000);
        servParamMap.put("opNote", opNote);
        servParamMap.put("opType", opType);

        // 查询原队列建档内容
        mapIn.put("newQueueId", newQueueId);
        Map<String, Object> valuesArchive = new HashMap<String, Object>();
        Map<String, Object> dataOut = this.getArchiveContValues(mapIn);
        if (MapUtils.isNotEmpty(dataOut)) {
            valuesArchive = ToolUtils.typeCast(dataOut.get("values"));
        }

        // 获取新队列建档内容
        List<Object> quesList = new ArrayList<Object>();
        Map<String, Object> contIn = new HashMap<String, Object>();
        contIn.put("followQueueId", newQueueId);
        contIn.put("schemeBusiType", schemeBusiType);
        contIn.put("followSchemeId", fqVo.getSchemeId());
        Map<String, Object> contOut = this.getArchiveContQues(contIn);
        if (MapUtils.isNotEmpty(contOut)) {
            quesList = ToolUtils.typeCast(contOut.get("questiones"));
        }
        if (CollectionUtils.isEmpty(quesList)) {
            // 建档问卷为空
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_IS_NULL, "新队列的建档问卷内容为空！");
        }

        // 按新队列建档问卷，从老队列建档答案和出院登记中获取信息
        Map<String, Object> matchIn = new HashMap<String, Object>();
        Map<String, Object> valuesMap = new HashMap<String, Object>();
        // 出院登记（或其他）
        valuesMap.putAll(contValues);
        if (MapUtils.isNotEmpty(valuesArchive)) {
            // 建档
            valuesMap.putAll(valuesArchive);
        }
        matchIn.put("valuesMap", valuesMap);
        matchIn.put("quesList", quesList);
        Map<String, Object> matchOut = this.dealQuesMatchValue(matchIn);
        servParamMap.put("contentData", matchOut);

        if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
            // 优先支持科研随访
            retOut = PatientService.registerPatient(servParamMap);
        } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
            // 后续支持
        } else {
            //
        }

        return retOut;
    }

    /**
     * @name: 获取建档资料
     * @author: DemonLee
     * @createTime: 2018.3.15
     * @description: 可能是随访建档，也可能是诊疗建档
     * @modify:
     */
    public Map<String, Object> getArchiveContValues(Map<String, Object> argIn) throws Exception {
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argIn);
        String ptSchemeId = (String) mapIn.get("ptSchemeId");
        String userId = (String) mapIn.get("userId");
        String queueId = (String) mapIn.get("queueId");
        // 队列信息
        Map<String, Object> queueInMap = new HashMap<String, Object>();
        queueInMap.put("id", queueId);
        List<FollowQueue> queueList = queueDao.selectById(queueInMap);
        if (CollectionUtils.isEmpty(queueList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到对应队列信息！"));
        }
        Map<String, Object> queueMapIn = new HashMap<String, Object>();
        queueMapIn.put("id", ptSchemeId);
        queueMapIn.put("queueId", queueId);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectPatientByCondition(queueMapIn);
        if (CollectionUtils.isEmpty(pqsList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "查询患者队列实例记录不存在！"));
        }

        FollowQueue fqVo = queueList.get(0);
        Integer schemeBusiType = fqVo.getSchemeBusiType();
        if (null == schemeBusiType) {
            // 默认科研随访
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0;
        }

        Map<String, Object> valuesMap = new HashMap<String, Object>();
        Map<String, Object> qryIn = new HashMap<String, Object>();
        if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
            // 科研随访
            qryIn.put("userId", userId);
            qryIn.put("ptSchemeId", ptSchemeId);
            qryIn.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
            List<PatientTask> ptVoList = patientTaskDao.select(qryIn);
            if (CollectionUtils.isEmpty(ptVoList)) {
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TASK_NOT_EXIST, "该患者建档任务不存在！");
            }
            Map<String, Object> valMapIn = new HashMap<String, Object>();
            valMapIn.put("taskId", ptVoList.get(0).getId());
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                PatientContentData pcdVo = null;
                int k = 0;
                for (; k < ptTaskConList.size(); k++) {
                    pcdVo = ptTaskConList.get(k);
                    valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                }
            }
        } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
            // 诊疗
            qryIn.put("ptTaskId", pqsList.get(0).getArchiveTaskId());
            List<PtArchiveData> ptTaskConList = ptArchiveDataDao.listPtArchiveData(qryIn);
            if (!CollectionUtils.isEmpty(ptTaskConList)) {
                PtArchiveData padVo = null;
                int tt = 0;
                for (; tt < ptTaskConList.size(); tt++) {
                    padVo = ptTaskConList.get(tt);
                    valuesMap.put(padVo.getQuestionId(), padVo.getQuestionAnswer());
                }
            }
        } else {
            // 后续支持
        }
        retOut.put("values", valuesMap);

        return retOut;
    }

    /**
     * @name: 获取建档问卷
     * @author: DemonLee
     * @createTime: 2018.3.15
     * @description: 可能是随访建档，也可能是诊疗建档
     * @modify:
     */
    public Map<String, Object> getArchiveContQues(Map<String, Object> argIn) throws Exception {
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argIn);
        Map<String, Object> qryMap = new HashMap<String, Object>();

        String followQueueId = (String) mapIn.get("followQueueId");
        String followSchemeId = (String) mapIn.get("followSchemeId");
        Integer schemeBusiType = (Integer) mapIn.get("schemeBusiType");
        if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
            // 科研随访
            qryMap.put("schemeId", followSchemeId);
            qryMap.put("queueId", followQueueId);

            retOut = followQueueSerivce.qryQueueSchemePatientAddContent(qryMap);
        } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
            // 诊疗
            qryMap.put("followQueueId", followQueueId);
            retOut = patientTreatService.getQueueArchiveContent(qryMap);
        } else {
            // 后续支持
        }

        return retOut;
    }

    /**
     * @name: 按问卷匹配答案
     * @author: DemonLee
     * @createTime: 2018.3.15
     * @description:
     * @modify:
     */
    public Map<String, Object> dealQuesMatchValue(Map<String, Object> argIn) throws Exception {
        Map<String, Object> retOut = new HashMap<String, Object>();
        Map<String, Object> mapIn = new HashMap<String, Object>(argIn);

        Map<String, Object> valuesMap = ToolUtils.typeCast(mapIn.get("valuesMap"));
        List<Object> quesList = ToolUtils.typeCast(mapIn.get("quesList"));
        // 问卷解析出问题id
        Map<String, Object> quesIdMap = ToolUtils.tranferContentToMap(quesList);
        // 按问题id找答案
        Iterator<String> iter = quesIdMap.keySet().iterator();
        String quesId = "";
        Object quesValue = "";
        while (iter.hasNext()) {
            quesId = iter.next();
            quesValue = valuesMap.get(quesId);
            if (null == quesValue) {
                continue;
            } else {
                retOut.put(quesId, quesValue);
            }
        }
        logger.debug("--match...retOut==" + retOut + ", retOut.size==" + retOut.size());

        return retOut;
    }

    /**
     * @name: 查询填写记录
     * @author: wuyz
     * @createTime: 2017.8.17
     * @description:查询门诊诊疗任务填写记录，支持分页，如果没有传入分页标识，默认查询前100条
     * @modify: 2017.09.28: DemonLee 门诊记录修改为全部该患者所有任务的list，不是某一项任务的list
     *          2017.11.16: DemonLee (1)按检查日期排序 (2)按日与任务进行分组，即同一天的相同的任务放一组
     */
    @Override
    public Map<String, Object> getOprationHistoryList(Map<String, Object> argIn) throws Exception {
        Map<String, Object> mapIn = new HashMap<String, Object>(argIn);
        Map<String, Object> mapOut = new HashMap<String, Object>();
        String taskId = (String) mapIn.get("taskId");
        String ptSchemeId = (String) mapIn.get("ptShemeId");
        /**
         * 取到队列id，解决一个用户加入多个队列，导致查询混乱的问题
         *
         * @modify 2017-10-28 wuyz
         **/
        String queueId = (String) mapIn.get("queueId");
        int total = 0;
        Integer schemeBusiType = (Integer) mapIn.get("schemeBusiType");
        List<PtTrTask> list = new ArrayList<PtTrTask>();
        List<Map<String, Object>> finishYearList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> dateTaskList = new ArrayList<Map<String, Object>>();
        if (schemeBusiType == Constants.SCHEME_BUSI_TYPE_1) {
            // 患者全部任务的记录list
            mapIn.remove("taskId");
            total = IPtTrTaskDAO.getOprationHistoryTotal(mapIn);
            if (total > 0) {
                list = IPtTrTaskDAO.getOprationHistoryList(mapIn);
                // 按年分组
                finishYearList = IPtTrTaskDAO.listOprationHistoryGroupBy(mapIn);
                // 按完成日期+任务分组
                dateTaskList = IPtTrTaskDAO.listOprationHisGroupByDate(mapIn);
            }
        } else {
            //
        }

        // 从队列实例信息获取建档任务时间
        String archiveFinishYear = "";
        PtTrTask ptTrArchTaskVo = new PtTrTask();
        Map<String, Object> queueMapIn = new HashMap<String, Object>();
        queueMapIn.put("id", ptSchemeId);
        queueMapIn.put("queueId", queueId);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectPatientByCondition(queueMapIn);
        if (!CollectionUtils.isEmpty(pqsList)) {
            PatientQueueScheme pqsVo = pqsList.get(0);
            ptTrArchTaskVo.setAuthorId(pqsVo.getAuthorId());
            ptTrArchTaskVo.setCreateTime(pqsVo.getCreateTime());
            ptTrArchTaskVo.setFinishDate(DateUtil.getTimeStampDay(pqsVo.getCreateTime()));
            ptTrArchTaskVo.setFinishTime(DateUtil.getTimeStampDay(pqsVo.getCreateTime()));
            ptTrArchTaskVo.setPtSchemeId(ptSchemeId);
            ptTrArchTaskVo.setQueueId(pqsVo.getQueueId());
            ptTrArchTaskVo.setSchemeVersionid(pqsVo.getSchemeVersionid());
            ptTrArchTaskVo.setSeqNo(0);
            ptTrArchTaskVo.setId(pqsVo.getArchiveTaskId());
            ptTrArchTaskVo.setTaskIntro("患者建档");
            ptTrArchTaskVo.setTaskName("患者建档");
            ptTrArchTaskVo.setTaskRecordName("患者建档");
            ptTrArchTaskVo.setUserId(pqsVo.getUserId());
            archiveFinishYear = ptTrArchTaskVo.getFinishDate().substring(0, 4);
        } else {
            return mapOut;
        }

        // 按年分组进行处理，将同一年的数据放在同一个list里面
        int yearFlag = 0;
        List<Object> outList = new ArrayList<Object>();
        if (!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(finishYearList)) {
            Map<String, Object> finishYearMap = new HashMap<String, Object>();
            int t = 0;
            int tsize = list.size();
            int f = 0;
            int fsize = finishYearList.size();
            int d = 0;
            int dsize = dateTaskList.size();
            // 年
            for (f = 0; f < fsize; f++) {
                finishYearMap = finishYearList.get(f);
                Map<String, Object> yearMap = new HashMap<String, Object>();
                String groupFinishYear = (String) finishYearMap.get("finishYear");
                if (StringUtils.isBlank(groupFinishYear)) {
                    continue;
                }
                yearMap.put("year", groupFinishYear);
                List<Map<String, Object>> yearList = new ArrayList<Map<String, Object>>();
                yearMap.put("yearList", yearList);
                String finishTime = "";
                String finishYear = "";
                // 日
                for (d = 0; d < dsize; d++) {
                    Map<String, Object> dateTaskMap = dateTaskList.get(d);
                    String finishDate = (String) dateTaskMap.get("finishDate");
                    String currTaskId = (String) dateTaskMap.get("taskId");
                    List<PtTrTask> dateTaskListNew = new ArrayList<PtTrTask>();
                    dateTaskMap.put("dateList", dateTaskListNew);

                    for (t = 0; t < tsize; t++) {
                        // 老数据处理，使用task_name,finish_time来替代
                        PtTrTask ptTrTaskVo = list.get(t);
                        if (StringUtils.isBlank(ptTrTaskVo.getTaskRecordName())) {
                            ptTrTaskVo.setTaskRecordName(ptTrTaskVo.getTaskName());
                        }
                        if (StringUtils.isBlank(ptTrTaskVo.getFinishDate())) {
                            finishTime = ptTrTaskVo.getFinishTime();
                            if (StringUtils.isBlank(finishTime)) {
                                finishTime = ptTrTaskVo.getCreateTime();
                            }
                            ptTrTaskVo.setFinishDate(DateUtil.getTimeStampDay(finishTime));
                        }

                        if (ptTrTaskVo.getFinishDate().equals(finishDate)
                                && ptTrTaskVo.getTaskId().equals(currTaskId)) {
                            dateTaskListNew.add(ptTrTaskVo);
                        }
                    }

                    finishYear = finishDate.substring(0, 4);
                    if (groupFinishYear.equals(finishYear)) {
                        yearList.add(dateTaskMap);
                    }
                }

                Map<String, Object> archiveMap = new HashMap<String, Object>();
                if (archiveFinishYear.equals(groupFinishYear)) {
                    archiveMap.put("finishDate", ptTrArchTaskVo.getFinishDate());
                    archiveMap.put("taskId", ptTrArchTaskVo.getTaskId());
                    List<PtTrTask> dateTaskListNew = new ArrayList<PtTrTask>();
                    archiveMap.put("dateList", dateTaskListNew);
                    dateTaskListNew.add(ptTrArchTaskVo);
                    yearList.add(archiveMap);

                    yearFlag = 1;
                }
                outList.add(yearMap);
            }
        }

        if (StringUtils.isNotBlank(archiveFinishYear) && 0 == yearFlag) {
            // 建档记录
            Map<String, Object> archiveMap = new HashMap<String, Object>();
            Map<String, Object> yearMap = new HashMap<String, Object>();
            List<Map<String, Object>> yearList = new ArrayList<Map<String, Object>>();

            yearMap.put("year", archiveFinishYear);
            yearMap.put("yearList", yearList);

            archiveMap.put("finishDate", ptTrArchTaskVo.getFinishDate());
            archiveMap.put("taskId", ptTrArchTaskVo.getTaskId());
            List<PtTrTask> dateTaskListNew = new ArrayList<PtTrTask>();
            archiveMap.put("dateList", dateTaskListNew);
            dateTaskListNew.add(ptTrArchTaskVo);
            yearList.add(archiveMap);

            outList.add(yearMap);
        }

        // 患者当前任务的今天记录list
        List<TrTask> trTaskList = new ArrayList<TrTask>();
        if (StringUtils.isNotBlank(taskId)) {
            Map<String, Object> taskQueryParam = new HashMap<String, Object>();
            taskQueryParam.put("Id", taskId);
            trTaskList = trTaskDao.listTrTaskBySchemeVersionid(taskQueryParam);
        }
        List<PtTrTask> listNow = new ArrayList<PtTrTask>();
        if (StringUtils.isNotBlank(taskId) && !CollectionUtils.isEmpty(trTaskList)) {
            String finishTime = DateUtil.getCurrDate2();
            mapIn.put("finishTime", finishTime);
            mapIn.put("taskId", taskId);
            listNow = IPtTrTaskDAO.getOprationHistoryList(mapIn);
            if (!CollectionUtils.isEmpty(listNow)) {
                mapOut.put("flag", "1");
            } else {
                mapOut.put("flag", "0");
            }

            // 后台根据当前任务的记录数，自动计算出新建一笔的任务名称
            mapIn.remove("finishTime");
            int currTotal = IPtTrTaskDAO.getOprationHistoryTotal(mapIn);

            TrTask trTaskVo = trTaskList.get(0);
            StringBuffer strBuffer = new StringBuffer();
            strBuffer.append(trTaskVo.getTaskName());
            strBuffer.append("(");
            strBuffer.append(currTotal + 1);
            strBuffer.append(")");
            mapOut.put("defTaskRecordName", strBuffer.toString());
        } else {
            mapOut.put("flag", "");
            mapOut.put("defTaskRecordName", "");
        }

        mapOut.put("toadyCurrList", listNow);
        mapOut.put("rows", outList);
        mapOut.put("total", total + 1);

        return mapOut;
    }

    /**
     * @name: 填写记录详情查询
     * @author: wuyz
     * @createTime: 2017.8.17
     * @description:查询门诊诊疗详细信息，和当前任务模板
     * @modify:
     *
     */
    @Override
    public Map<String, Object> getOprationHistory(Map<String, Object> mapIn) throws Exception {
        logger.info("getOprationHistory :: " + mapIn.toString());
        int schemeBusiType = (Integer) mapIn.get("schemeBusiType");
        // 查询当前用户的任务信息
        Map<String, Object> mapOut = new HashMap<String, Object>();
        List<PtTrTask> list = new ArrayList<PtTrTask>();
        if (schemeBusiType == Constants.SCHEME_BUSI_TYPE_1) {
            list = IPtTrTaskDAO.getOprationHistory(mapIn);
        }
        // 查询当前记录任务模板信息
        String taskId = String.valueOf(mapIn.get("taskId"));
        if (!StringUtils.isBlank(String.valueOf(taskId)) && !"null".equals(taskId)) {
            List<TrTaskContent> lists = ITrTaskContentDao.getTaskContentByTaskId(mapIn);
            if (lists != null && lists.size() > 0) {
                String archiveTemplId = "";
                for (int i = 0; i < lists.size(); i++) {
                    TrTaskContent tc = lists.get(i);
                    archiveTemplId = archiveTemplId + "," + tc.getTemplId();
                }
                String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
                List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
                Map<String, Object> contMapIn = new HashMap<String, Object>();
                contMapIn.put("templIdList", archiveTemplIdList);
                Map<String, Object> contMapOut = PatientTreatService.getContentTemplData(contMapIn);
                mapOut.put("questiones", contMapOut.get("questiones"));
            }
        } else {
            if (list == null || list.size() <= 0) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "当前无此门诊诊疗任务！"));
            } else {
                mapIn.put("taskId", list.get(0).getTaskId());
                List<TrTaskContent> lists = ITrTaskContentDao.getTaskContentByTaskId(mapIn);
                if (lists != null && lists.size() > 0) {
                    String archiveTemplId = "";
                    for (int i = 0; i < lists.size(); i++) {
                        TrTaskContent tc = lists.get(i);
                        archiveTemplId = archiveTemplId + "," + tc.getTemplId();
                    }
                    String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
                    List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
                    Map<String, Object> contMapIn = new HashMap<String, Object>();
                    contMapIn.put("templIdList", archiveTemplIdList);
                    Map<String, Object> contMapOut = PatientTreatService.getContentTemplData(contMapIn);
                    mapOut.put("questiones", contMapOut.get("questiones"));
                }
            }

        }
        // 查询当前记录的详细填写的详细信息
        List<PtTrContentData> ptTaskConList = new ArrayList<PtTrContentData>();
        Map<String, Object> questionMap = new HashMap<String, Object>();
        ptTaskConList = IPtTrContentDataDAO.getTaskContent(mapIn);
        if (!CollectionUtils.isEmpty(ptTaskConList)) {
            int k = 0;
            for (; k < ptTaskConList.size(); k++) {
                PtTrContentData pcdVo = ptTaskConList.get(k);
                questionMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
            }

            mapIn.put("ptSchemeId", ptTaskConList.get(0).getPtSchemeId());
            List<PtArchiveTask> ptVoList = ptArchiveTaskDao.listPtArchiveTask(mapIn);
            if (!CollectionUtils.isEmpty(ptVoList)) {
                // 患者建档问卷答案信息
                Map<String, Object> cntMap = new HashMap<String, Object>();
                cntMap.put("ptTaskId", ptVoList.get(0).getId());
                List<PtArchiveData> ptConList = ptArchiveDataDao.listPtArchiveData(cntMap);
                if (!CollectionUtils.isEmpty(ptConList)) {
                    int tt = 0;
                    for (; tt < ptConList.size(); tt++) {
                        PtArchiveData pcdVo = ptConList.get(tt);
                        questionMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
                    }
                }
            }

        }
        mapOut.put("values", questionMap);
        mapOut.put("taskInfo", list);
        return mapOut;
    }

    // 患者队列信息接口实现
    @Override
    public HashMap<String, Object> qryPatientQueueSchemeList(Map<String, Object> paramMap) throws Exception {
        HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
        String flag = (String) argMap.get("flag");
        String tenantId = (String) argMap.get("tenantId");
        String fuzzyVar = (String) argMap.get("fuzzyVar");
        int total = 0;
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        List<Map<String, Object>> pqsList = new ArrayList<Map<String, Object>>();
        retMap.put("total", 0);
        retMap.put("rows", pqsList);

        // 若有服务号码或患者姓名，则先获取患者id串（可能有多个）
        List<String> userIdArray = new ArrayList<String>();
        int qryUserFlag = 0;
        String phoneNo = (String) argMap.get("phoneNo");
        String userName = (String) argMap.get("userName");// 可以是姓氏或姓名
        HashMap<String, Object> qryUserMap = new HashMap<String, Object>();
        if (null != phoneNo && !"".equals(phoneNo) && StringUtils.isEmpty(fuzzyVar)) {
            qryUserMap.put("phoneNo", phoneNo);
            qryUserFlag = 1;
        }
        if (null != userName && !"".equals(userName)) {
            argMap.put("userName", userName + "%");
        }
        if (1 == qryUserFlag) {
            List<Patient> ptList = patientDao.select(qryUserMap);
            if (null == ptList || 0 == ptList.size()) {
                logger.warn("无此患者信息...arg==" + qryUserMap.toString());
                return retMap;
            }
            int ipt = 0;
            for (; ipt < ptList.size(); ipt++) {
                Patient ptVo = ptList.get(ipt);
                // 后续sql中用in条件处理（这里先不考虑返回结果超过1000个）
                userIdArray.add(ptVo.getId());
            }
        }
        logger.warn("userIdArray==" + userIdArray.toString());

        // 根据当前登录账号获取，其可以查看的队列id（权限处理比较复杂，这里先简化）
        String authorId = (String) argMap.get("authorId");
        HashMap<String, Object> qryQueueMap = new HashMap<String, Object>();
        qryQueueMap.put("authorId", authorId);
        qryQueueMap.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);// 队列状态正常
        qryQueueMap.put("tenantId", tenantId);
        qryQueueMap.put("queueTypePrivate", Constants.QUEUE_TYPE_PRIVATE);
        qryQueueMap.put("queueTypeTenant", Constants.QUEUE_TYPE_TENANT);
        qryQueueMap.put("queueTypePublic", Constants.QUEUE_TYPE_PUBLIC);

        List<FollowQueue> fqList = null;
        // 1：如果传入队列 则直接用队列查询 2：没有传入队列ID 则根据权限先查询 该用户有哪些队列权限 再查询
        String queueId = (String) argMap.get("queueId");
        String queueName = "";
        if (!StringUtils.isBlank(queueId)) {
            Map<String, Object> queueMap = new HashMap<String, Object>();
            queueMap.put("id", queueId); // 租户id先写死
            fqList = queueDao.selectById(queueMap);
        } else {
            List<Map<String, Object>> lists = IConfCacheDAO.selectAuthorId(qryQueueMap);
            if (lists != null && lists.size() > 0 && !"0".equals((String) argMap.get("showFlag"))) {
                fqList = queueDao.selectQueueIdByparentId(qryQueueMap);
                for (int j = 0; j < fqList.size(); j++) {
                    if (authorId.equals(fqList.get(j).getAuthorId())) {
                        queueName = fqList.get(j).getQueueName();
                    }
                }
            } else {
                fqList = queueDao.selectQueueIdByAuthority(qryQueueMap);
            }

        }

        if (null == fqList || 0 == fqList.size()) {
            logger.warn("该账号无可查看到的队列信息...arg==" + qryQueueMap.toString());
            return retMap;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(Constants.REDIS_DB_INDEX_CONFIG);
            // HashMap<String, String> queueInfoMap = new HashMap<String,
            // String>();
            List<String> queueIdArray = new ArrayList<String>();
            int fqt = 0;
            for (; fqt < fqList.size(); fqt++) {
                FollowQueue fqVo = fqList.get(fqt);
                // 后续sql中用in条件处理（这里先不考虑返回结果超过1000个）
                queueIdArray.add(fqVo.getId());
            }

            // 获取随访患者list
            argMap.put("queueIdIn", queueIdArray);
            if (0 != userIdArray.size()) {
                argMap.put("userIdIn", userIdArray);
            }
            // 今日待随访患者flag=0（即今天在窗口期内的患者都算）
            if ("0".equals(flag)) {
                argMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
                argMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);// 未开始的任务
                argMap.put("endTime", DateUtil.getCurrDate());// 截止时间>=当前时间
                argMap.put("beginTime", DateUtil.getCurrDate());// 开始时间<=当前时间
                argMap.put("taskExistsFlag", "1");
                argMap.put("orderByCreateTime", "1");
                argMap.put("initTaskRev", "1");
                argMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务

                total = patientQueueSchemeDao.countTotalPtQueueNumByCondition(argMap);
                if (total > 0) {
                    pqsList = patientQueueSchemeDao.selectPtQueueList(argMap);

                    if (null == pqsList || 0 == pqsList.size()) {
                        // 数据被删除或改变了
                        total = 0;
                    } else {
                        HashSet<String> fristNameSet = new HashSet<String>();

                        // 使用set容器对姓氏剔重
                        int pq = 0;
                        String pqsQueueId = "";
                        String patientSchemeId = "";
                        Map<String, Object> qryMapIn = new HashMap<String, Object>();
                        Map<String, Object> qryMapOut = new HashMap<String, Object>();
                        Map<String, Object> ptMapIn = new HashMap<String, Object>();
                        for (; pq < pqsList.size(); pq++) {
                            Map<String, Object> pqsMap = pqsList.get(pq);
                            String firstName = (String) pqsMap.get("FirstName");
                            fristNameSet.add(firstName);

                            // 获取队列名称
                            pqsQueueId = (String) pqsMap.get("followQueueId");
                            qryMapIn.clear();
                            qryMapIn.put("queueId", pqsQueueId);
                            qryMapOut = PatientService.getQueueName(qryMapIn, jedis);
                            pqsMap.put("followQueueName", qryMapOut.get("queueName"));

                            // 获取方案下所有任务的完成情况
                            int ptsize = 0;
                            int kk = 0;
                            patientSchemeId = (String) pqsMap.get("patientSchemeId");
                            ptMapIn.clear();
                            ptMapIn.put("ptSchemeId", patientSchemeId);
                            ptMapIn.put("seqNoOrderAsc", "1");
                            ptMapIn.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
                            List<Map<String, Object>> mapOutList = patientTaskDao.selectTaskStatusByPtSchemeId(ptMapIn);
                            if (CollectionUtils.isEmpty(mapOutList) || MapUtils.isEmpty(mapOutList.get(0))) {
                                // 无任务信息，异常情况
                                ptsize = Integer.parseInt("" + pqsMap.get("totalNum"));
                                if (ptsize <= 0) {
                                    pqsMap.put("taskStatusArr", "[]");
                                } else {
                                    StringBuffer strStatus = new StringBuffer();
                                    strStatus.append("[");
                                    for (kk = 0; kk < ptsize; kk++) {
                                        strStatus.append("0,");
                                    }
                                    String strStr = strStatus.substring(0, strStatus.length() - 1);
                                    pqsMap.put("taskStatusArr", strStr + "]");
                                }
                            } else {
                                pqsMap.put("taskStatusArr", mapOutList.get(0).get("taskStatusArr"));
                            }
                        }

                        StringBuffer firstNameValue = new StringBuffer();
                        Iterator<String> itor = fristNameSet.iterator();
                        while (itor.hasNext()) {
                            firstNameValue.append(itor.next());
                            firstNameValue.append(",");
                        }
                        retMap.put("FirstName", firstNameValue.substring(0, firstNameValue.length() - 1));
                    }
                }
            } else if ("2".equals(flag)) {
                // 当前账号可以看到的所有患者list（flag=2）
                argMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
                argMap.put("orderByCreateTime", "1");
                List<String> taskTypeInList = new ArrayList<String>();
                taskTypeInList.add(Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
                taskTypeInList.add(Constants.TASK_TYPE_SCHEME_TEMP);// 线上随访（暂时放开）
                argMap.put("taskTypeIn", taskTypeInList);

                // 根据孕周查询
                total = patientQueueSchemeDao.countTotalPtQueueNumByCondition(argMap);
                if (total > 0) {
                    pqsList = patientQueueSchemeDao.selectPtQueueList(argMap);
                    if (null == pqsList || 0 == pqsList.size()) {
                        // 数据被删除或改变了
                        total = 0;
                    } else {
                        int pq = 0;
                        String pqsQueueId = "";
                        String patientSchemeId = "";
                        Map<String, Object> qryMapIn = new HashMap<String, Object>();
                        Map<String, Object> qryMapOut = new HashMap<String, Object>();
                        Map<String, Object> ptMapIn = new HashMap<String, Object>();
                        for (; pq < pqsList.size(); pq++) {
                            Map<String, Object> pqsMap = pqsList.get(pq);

                            // 获取队列名称
                            pqsQueueId = (String) pqsMap.get("followQueueId");
                            qryMapIn.clear();
                            qryMapIn.put("queueId", pqsQueueId);
                            qryMapOut = PatientService.getQueueName(qryMapIn, jedis);
                            qryMapIn.put("id", pqsQueueId);
                            List<FollowQueue> flq = queueDao.selectById(qryMapIn);
                            pqsMap.put("followQueueName", qryMapOut.get("queueName"));
                            if (!StringUtils.isBlank(queueName) && !queueName.equals(qryMapOut.get("queueName"))
                                    && Constants.LOST_REASON_TYPE_PRIVATE.equals(flq.get(0).getQueueType())) {
                                pqsMap.put("unchecked", "1");
                            } else {
                                pqsMap.put("unchecked", "0");

                            }
                            qryMapIn.put("patientSchemeId", (String) pqsMap.get("patientSchemeId"));
                            qryMapIn.put("userId", (String) pqsMap.get("patientId"));
                            // 微信月度评估兼容返回出生体重
                            List<PatientContentData> lists = patientTaskConDao
                                    .listCntDataByUserIdAndAcceptPrivate(qryMapIn);
                            if (!CollectionUtils.isEmpty(lists)) {
                                for (int j = 0; j < lists.size(); j++) {
                                    if (Constants.QUESTION_ID_FOR_WEIGHT.equals(lists.get(j).getQuestionId())) {
                                        pqsMap.put("weight", lists.get(j).getQuestionAnswer());
                                    }
                                }
                            }
                            // 获取方案名称
                            qryMapIn.clear();
                            qryMapIn.put("schemeId", (String) pqsMap.get("schemeId"));
                            qryMapOut = PatientService.getSchemeName(qryMapIn, jedis);
                            pqsMap.put("schemeName", qryMapOut.get("schemeName"));

                            // 孕周计算
                            /*
                             * pqsMap.put("pregnancyWeek", Integer.parseInt("" +
                             * pqsMap.get("pregnancyDay")) /
                             * Constants.PREGNANCY_CALC_UNIT_WEEK);
                             */
                            pqsMap.put("createTime", DateUtil.getTimeStampDay(pqsMap.get("createTime").toString()));
                            // 年龄
                            if (!StringUtils.isEmpty("" + pqsMap.get("pregnancyDay"))) {
                                String pregnancy = "" + pqsMap.get("pregnancyDay");
                                long correctAge = ToolUtils.getCorrect(String.valueOf(pqsMap.get("birthday")),
                                        Integer.parseInt(pregnancy));

                                Date date = new Date(correctAge);
                                pqsMap.put("age", ToolUtils.getAgeByBirthday(DateUtil.getDate_8(date)));
                                pqsMap.put("pregnancyWeek",
                                        ToolUtils.getPregnancyStr(Integer.parseInt("" + pqsMap.get("pregnancyDay"))));
                            } else {// 孕周为空 则按正常年龄算
                                pqsMap.put("age", ToolUtils.getAgeByBirthday("" + pqsMap.get("birthday")));
                            }

                            // 获取方案下所有任务的完成情况
                            int ptsize = 0;
                            int kk = 0;
                            patientSchemeId = (String) pqsMap.get("patientSchemeId");
                            ptMapIn.clear();
                            ptMapIn.put("ptSchemeId", patientSchemeId);
                            ptMapIn.put("seqNoOrderAsc", "1");
                            ptMapIn.put("taskTypeIn", taskTypeInList);
                            List<Map<String, Object>> mapOutList = patientTaskDao.selectTaskStatusByPtSchemeId(ptMapIn);
                            if (CollectionUtils.isEmpty(mapOutList) || MapUtils.isEmpty(mapOutList.get(0))) {
                                // 无任务信息，异常情况
                                ptsize = Integer.parseInt("" + pqsMap.get("totalNum"));
                                if (ptsize <= 0) {
                                    pqsMap.put("taskStatusArr", "[]");
                                } else {
                                    StringBuffer strStatus = new StringBuffer();
                                    strStatus.append("[");
                                    for (kk = 0; kk < ptsize; kk++) {
                                        strStatus.append("0,");
                                    }
                                    String strStr = strStatus.substring(0, strStatus.length() - 1);
                                    pqsMap.put("taskStatusArr", strStr + "]");
                                }
                            } else {
                                pqsMap.put("taskStatusArr", mapOutList.get(0).get("taskStatusArr"));
                            }
                        }
                    }
                }
            } else if ("3".equals(flag)) {
                // flag=3 随访记录查询，每个随访的患者多次记录，只展示最后一次
                argMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_FINISH);// 已完成的任务
                argMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
                argMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务

                total = patientQueueSchemeDao.countPatientTaskFinishInfoOutpatient(argMap);
                if (total > 0) {
                    pqsList = patientQueueSchemeDao.selectPatientTaskFinishInfoOutpatient(argMap);
                    if (null == pqsList || 0 == pqsList.size()) {
                        // 数据被删除或改变了
                        total = 0;
                    } else {
                        int pq = 0;
                        String pqsQueueId = "";
                        Map<String, Object> qryMapIn = new HashMap<String, Object>();
                        Map<String, Object> qryMapOut = new HashMap<String, Object>();
                        for (; pq < pqsList.size(); pq++) {
                            Map<String, Object> pqsMap = pqsList.get(pq);

                            // 获取队列名称
                            pqsQueueId = (String) pqsMap.get("followQueueId");
                            qryMapIn.clear();
                            qryMapIn.put("queueId", pqsQueueId);
                            qryMapOut = PatientService.getQueueName(qryMapIn, jedis);
                            pqsMap.put("followQueueName", qryMapOut.get("queueName"));

                            pqsMap.put("pregnancyWeek",
                                    ToolUtils.getPregnancyStr(Integer.parseInt("" + pqsMap.get("pregnancyDay"))));
                        }
                    }
                }
            }
        } catch (JedisConnectionException jex) {
            logger.error("redis连接异常..." + jex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
        } finally {
            if (null != jedis) {
                try {
                    jedis.close();
                    logger.warn("close redis connection...");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
                            "Redis缓存关闭失败!"));
                }
            }
        }

        retMap.put("total", total);
        retMap.put("rows", pqsList);

        return retMap;
    }

}
